<script setup lang="ts">
import { cloneDeep } from 'lodash-es'
import { Echart } from '@fl/origin-components/Echart'
import { useBIFinishRate } from '@fl/api/add-elevator-api'
// import countTo from 'vue-count-to'
// 新
import circle1 from '@/assets/images/circle1.png'
import circle2 from '@/assets/images/circle2.png'
import circle3 from '@/assets/images/circle3.png'
import circle4 from '@/assets/images/circle4.png'
import circle5 from '@/assets/images/circle5.png'
import circleLeft from '@/assets/images/circle-left.png'
import circleRight from '@/assets/images/circle-right.png'

const areaCode = defineModel<string>('areaCode', { required: true })
const mapList = defineModel<any>('mapList', { required: true, default: [] })
const percentage = ref<string>('0.00')
const rightChartsCount = ref<number>(0)
const current = ref<string>('submitNum')
const sortedData = ref<any>([])

const rightCharts = ref({
    legend: {
        orient: 'vertical',
        right: 10, // 距离右侧 5% 的宽度
        top: 'middle', // 等同于 'center'
        itemGap: 10, // 图例项之间的间隔（可选）
        itemWidth: 10, // 图例标记的宽度（可选）
        itemHeight: 10,
        icon: 'circle', // 图标设置为圆形
        type: 'scroll',
        height: '80%',
        formatter(name) {
            const data = sortedData.value.slice(0, 5).find(item => item.name === name)
            if (!data) {
                return name // 如果找不到数据，则显示原始名称
            }
            const percentage = Number.isFinite(rightChartsCount.value) && rightChartsCount.value !== 0
                ? `${((data.value / rightChartsCount.value) * 100).toFixed(2)}%`
                : '0.00%'

            return `{container|${data.name}} {middle|${data.value}}  {right|${percentage}}`
        },
        textStyle: {
            rich: {
                container: {
                    // width: 145,
                    // fontSize: 14,
                    align: 'left',
                },
                middle: {
                    // width: 20,
                    // fontSize: 14,
                    align: 'right',

                },
                right: {
                    // width: 60,
                    // fontSize: 14,
                    align: 'right',
                },
            },
            color: '#fff',
        },
    },
    tooltip: {
        trigger: 'item',
    },
    series: [
        {
            type: 'pie',
            padAngle: 5,
            itemStyle: {
                borderRadius: 2,
            },
            radius: ['40%', '50%'],
            center: ['26%', '50%'],
            tooltip: {
                trigger: 'item',
            },
            data: [],
            label: {
                show: false,
                position: 'center',
                color: '#fff',
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: 20,
                    fontWeight: 'bold',
                    formatter: '{b} \n {d}%',

                },
            },
            labelLine: {
                show: false,
            },
        },
    ],
})

const { data: finishData } = useBIFinishRate(areaCode)
watchEffect(() => {
    if (finishData.value && finishData.value.submitCount !== 0) {
        percentage.value = ((finishData.value.ownerCount / finishData.value.submitCount) * 100).toFixed(2)
        // console.log('percentage', finishData.value, percentage.value)
    }
    else {
        percentage.value = '0.00'
    }
    if (mapList.value.length) {
        console.log('watch3')
        getRightCharts(current.value)
    }
})

// watch(current, (val: any) => {
//     if (val) {
//         console.log('watch1', val)
//         setTimeout(() => {
//             getRightCharts(val)
//         }, 1000)
//     }
// }, {
//     immediate: true,
// })

// watch(areaCode, (val: any) => {
//     console.log('watch2', val)
//     setTimeout(() => {
//         getRightCharts('submitNum')
//     }, 1000)
// }, {
//     immediate: true,
// })

function getRightCharts(val) {
    if (mapList.value?.length === 0)
        return
    rightChartsCount.value = 0
    console.log('getRightCharts', val)
    sortedData.value = cloneDeep(mapList.value).sort((a, b) => {
        // 处理 null 值，将 null 视为最小值
        const valA = a[val] !== null ? a[val] : -Infinity
        const valB = b[val] !== null ? b[val] : -Infinity

        return valB - valA // 降序排序
    })
    // console.log('sortedData.value', sortedData.value)
    // 根据对应tab给value赋值
    const arr = sortedData.value.reduce((pre, cur) => {
        // cur.percentage = Math.round((cur.totalNum / total) * 100)
        cur.value = Number(cur[val])
        rightChartsCount.value += Number(cur[val]) // 对应tab总数
        pre.push(cur)
        return pre
    }, [])
    console.log('arr', arr, rightChartsCount.value)

    // console.log(val, rightChartsCount.value)
    // 排除前5个，处理为其他
    const otherValue = arr.slice(5).reduce((sum, item) => sum + item.value, 0)
    rightCharts.value.series[0].data = [
        ...sortedData.value.slice(0, 5),
        { name: '其他', value: otherValue },
    ]
    // console.log('rightCharts.value.series[0].data', rightCharts.value.series[0].data)
}

function switchTab(type) {
    current.value = type
}
</script>

<template>
    <div class="container">
        <div class="title">
            <span>业主意见征询完成率</span>
        </div>

        <div class="e-box e-box1">
            <div><span class="num">{{ percentage }}</span> %</div>

            <div>完成率</div>
            <!-- <countTo class="countto"
                     :start-val="0"
                     :end-val="percentage"
                     :duration="3000"
            /> -->
            <div class="position">
                <img class="circle1 middle"
                     :src="circle1"
                     alt=""
                >

                <img class="circle2 middle"
                     :src="circle2"
                     alt=""
                >

                <img class="circle3 middle"
                     :src="circle3"
                     alt=""
                >

                <img class="circle4"
                     :src="circle4"
                     alt=""
                >

                <img class="circle5"
                     :src="circle5"
                     alt=""
                >

                <img class="circle-left"
                     :src="circleLeft"
                     alt=""
                >

                <img class="circle-right"
                     :src="circleRight"
                     alt=""
                >
            </div>
        </div>

        <div class="title title2">
            <span>Top5区域分布</span>

            <el-button type="text"
                       class="tab-btn"
                       :class="{ active: current === 'submitNum' }"
                       @click="switchTab('submitNum')"
            >
                已上报
            </el-button>

            <el-button type="text"
                       class="tab-btn"
                       :class="{ active: current === 'processNum' }"
                       @click="switchTab('processNum')"
            >
                加装中
            </el-button>

            <el-button type="text"
                       class="tab-btn"
                       :class="{ active: current === 'num' }"
                       @click="switchTab('num')"
            >
                已加装
            </el-button>
        </div>

        <div class="e-box">
            <Echart id="rightCharts"
                    :options="rightCharts"
                    height="25em"
            />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.container {
    padding-right: 2em;
}

.title {
    display: flex;
    justify-content: end;
    padding-top: 1.5em;

    .tab-btn {
        width: 4.8em;
        height: 1.6em;
        background-image: url('@/assets/images/rectangle.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        color: #fff;
        font-size: 1.2em;
        padding: 0 0.4em;
        display: block;
        text-align: center;
        margin-left: -0.5em;

        &:hover,
        &.active {
            background-image: url('@/assets/images/rectangle-a.png');
        }
    }
}

.title2 {
    margin-top: 1.4em;
}

.e-box {
    width: 100%;
    height: 26em;
    margin: 0 0.2em 0.2em;
    background: linear-gradient(180deg, rgb(0 45 73 / 20%) 0%, #002d49 100%);
}

.e-box1 {
    height: 23.6em;
    // background-image: url('@/assets/images/statistic-bg1.png');
    background: linear-gradient(180deg, rgba(0, 45, 73, 0.2) 0%, #002d49 100%);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    position: relative;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    // align-items: center;
    div {
        font-size: 1em;

        .num {
            font-size: 2em;
            font-weight: bold;
            margin-left: 0.3em;
        }
    }
}
.position {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    img {
        position: absolute;
    }
    .middle {
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .circle1 {
        width: 12em;
        height: 12em;
    }
    .circle2 {
        width: 13em;
        height: 13em;
    }
    .circle3 {
        width: 24em;
        height: 7em;
        top: 30%;
    }
    .circle4 {
        position: absolute;
        width: 28em;
        height: 28em;
        right: 2%;
        top: 50%;
        transform: translateY(-50%);
    }
    .circle5 {
        position: absolute;
        width: 28em;
        height: 28em;
        left: 2%;
        top: 50%;
        transform: translateY(-50%);
    }
    .circle-left {
        width: 3em;
        position: absolute;
        top: 51%;
        left: 10%;
    }
    .circle-right {
        width: 3em;
        position: absolute;
        top: 51%;
        right: 10%;
    }
}
</style>
